using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rotempco.Core.ORM.Interfaces;
using System.Reflection;

namespace Rotempco.Core.ORM.ADAL
{
    public abstract class ADALFactory<TFactory>
        where TFactory : class, new()    
    {
        public static IDAL<TDomainObject, TPrimaryKey> GetInstance<TDomainObject, TPrimaryKey>() where TPrimaryKey : struct, IComparable
        {
            PropertyInfo propertyInfo = typeof(TFactory).GetProperty(typeof(TDomainObject).Name);
            if (propertyInfo == null)
                return null;

            return (IDAL<TDomainObject, TPrimaryKey>)propertyInfo.GetGetMethod().Invoke(new TFactory(), null);
        }

        public static dynamic GetFactoryInstance(string entityClassName)
        {
            string baseClassAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            baseClassAssemblyName = baseClassAssemblyName.Replace("Core", "BaseClass");

            string typeName;
            Type type;

            Assembly[] assemblyList = AppDomain.CurrentDomain.GetAssemblies();
            Assembly assembly = (from a in assemblyList where a.FullName.Contains(baseClassAssemblyName) select a).First();

            typeName = baseClassAssemblyName + ".Managers." + entityClassName + "Manager";
            type = assembly.GetType(typeName);

            if (type != null)
                return Activator.CreateInstance(type);

            typeName = baseClassAssemblyName + ".DAL." + entityClassName + "Data";
            type = assembly.GetType(typeName);

            if (type != null)
                return Activator.CreateInstance(type);

            throw new Exception("EntiryClass " + entityClassName + " not found");
        }

    }
}
